package com.chang.common.validator;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.HashSet;
import java.util.Set;

/*
 * @Author Changzhenxi
 * @Date 2024/2/28 11:26
 * @Description 自定义注解的校验方法 实现接口的两个泛型，一个是
 * @Since version 1.0
 */
public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {
    /**
     * Initializes the validator in preparation for
     * {@link # isValid(Object, ConstraintValidatorContext)} calls.
     * The constraint annotation for a given constraint declaration
     * is passed.
     * <p>
     * This method is guaranteed to be called before any use of this instance for
     * validation.
     * <p>
     * The default implementation is a no-op.
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */

    private Set<Integer> set = new HashSet<>();

    //初始化方法 遍历规则数组，有就是1没有就是0
    @Override
    public void initialize(ListValue constraintAnnotation) {

        int[] value = constraintAnnotation.value();
        for (int val : value) {
            set.add(val);
        }
        //ConstraintValidator.super.initialize(constraintAnnotation);
    }

    /**
     * Implements the validation logic.
     * The state of {@code value} must not be altered.
     * <p>
     * This method can be accessed concurrently, thread-safety must be ensured
     * by the implementation.
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    // 判断是否校验成功  参数value及时需要校验的值
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {

        return set.contains(value); //判断实际传递过来的值有没有在规则数组中
    }
}
